package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.persistence.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {
  @Autowired
  private ItemMapper itemMapper;
  @Autowired
  private ProductMapper productMapper;
  @Autowired
  private OrderMapper orderMapper;
  @Autowired
  private SequenceMapper sequenceMapper;
  @Autowired
  private LineItemMapper lineItemMapper;
  @Autowired
  private CategoryMapper categoryMapper;
  @Autowired
  private CartMapper cartMapper;

  public OrderService(){
  }

  public void insertOrder(Order order) {
    order.setOrderId(getNextId("ordernum"));
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      String itemId = lineItem.getItemId();
      Integer increment = new Integer(lineItem.getQuantity());
      Map<String, Object> param = new HashMap<String, Object>(2);
      param.put("itemId", itemId);
      param.put("increment", increment);
      itemMapper.updateInventoryQuantity(param);
    }

    orderMapper.insertOrder(order);
    orderMapper.insertOrderStatus(order);
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = (LineItem) order.getLineItems().get(i);
      lineItem.setOrderId(order.getOrderId());
      lineItemMapper.insertLineItem(lineItem);
    }
  }

  public int getNextId(String name) {
    Sequence sequence = new Sequence(name, -1);
    sequence = sequenceMapper.getSequence(sequence);
    if (sequence == null) {
      throw new RuntimeException("Error: A null sequence was returned from the database (could not get next " + name
          + " sequence).");
    }
    Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
    sequenceMapper.updateSequence(parameterObject);
    return sequence.getNextId();
  }

  //后台
  //查询所有订单
  public List<Order> getOrders(){
    return orderMapper.getOrders();
  }

  //按用户查询订单
  public List<Order> getOrdersByUsername(String username) {
    return orderMapper.getOrdersByUsername(username);
  }

  //按时间查询订单
  public List<Order> getOrdersByOrderdate(String orderdate){
    return orderMapper.getOrdersByOrderdate(orderdate);
  }

  //按用户+时间查询订单
  public List<Order> getOrdersByUsernameAndOrderdate(String username,String orderdate){
    return orderMapper.getOrdersByUsernameAndOrderdate(username,orderdate);
  }

  //根据orderid显示某一个订单的具体信息
  public Order getOrder(int orderId) {
    Order order = orderMapper.getOrder(orderId);
    order.setLineItems(lineItemMapper.getLineItemsByOrderId(orderId));
    for (int i = 0; i < order.getLineItems().size(); i++) {
      LineItem lineItem = order.getLineItems().get(i);
      Item item = itemMapper.getItem(lineItem.getItemId());
      item.setQuantity(itemMapper.getInventoryQuantity(lineItem.getItemId()));
      lineItem.setItem(item);
    }
    return order;
  }

  //修改订单的Payment、Billing、Shipping信息
  public void updatePaymentAndBillingAndShipping(Order order){
    orderMapper.updatePaymentAndBillingAndShipping(order);
  }

  //删除订单
  public void removeOrder(int orderId){
    orderMapper.removeOrder(orderId);
  }

  //获得总价在A~B之间的订单的总数
  public int getNumOfOrderPriceBetweenAToB(int A,int B){
    BigDecimal a=BigDecimal.valueOf(A);
    BigDecimal b=BigDecimal.valueOf(B);
    List<Order> orderList=orderMapper.getNumberOfTotalPriceBetweenAToB(a,b);
    return orderList.size();
  }

  //获得每个种类的售卖宠物数量
  //两行A列，列数是动态的
  //第一行储存种类名，第二行储存售卖数量
  //可以使用category[0].length()获得列数
  public String[][] getNumOfCategorySell(){
    List<Category> categoryList=categoryMapper.getCategoryList();
    List<LineItem> lineItemList=lineItemMapper.getLineItems();
    int a=categoryList.size();
    String[][] category=new String[2][a];
    for(int i=0;i<a;i++){
      category[0][i]=categoryList.get(i).getCategoryId();
      category[1][i]="0";
    }
    for(int i=0;i<lineItemList.size();i++){
      int quantity=lineItemList.get(i).getQuantity();
      String itemId=lineItemList.get(i).getItemId();
      Item item= cartMapper.getItemByItemId(itemId);
      if(item!=null){
        String productId=item.getProductId();
        Product product= productMapper.getProduct(productId);
        if(product!=null){
          String categoryId=product.getCategoryId();
          for(int j=0;j<a;j++){
            if(categoryId.equals(category[0][j])){
              int x=Integer.parseInt(category[1][j]);
              x+=quantity;
              category[1][j]=String.valueOf(x);
            }
          }
        }else{
          System.out.println("Product找不到");
        }
      }else{
        System.out.println("Item找不到");
      }
    }
    return category;
  }
}
